package com.sita.bike.ui.activity.roadtrust;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.VideoView;

import com.danikula.videocache.HttpProxyCacheServer;
import com.sita.bike.R;
import com.sita.bike.support.GlobalContext;

public class VideoPlayerActivity extends AppCompatActivity implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, View.OnTouchListener {

    private VideoView mVV;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_video_player);

        String fileRes = "";
        Bundle e = getIntent().getExtras();
        if (e != null) {
            fileRes = e.getString("fileRes");
        }

        mVV = (VideoView) findViewById(R.id.video_player_view);
        mVV.setOnCompletionListener(this);
        mVV.setOnPreparedListener(this);
        mVV.setOnTouchListener(this);

        if (!playFileRes(fileRes)) return;

        mVV.start();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        String fileRes = "";
        Bundle e = getIntent().getExtras();
        if (e != null) {
            fileRes = e.getString("fileRes");
        }
        playFileRes(fileRes);
    }

    private boolean playFileRes(int fileRes) {
        if (fileRes == 0) {
            stopPlaying();
            return false;
        } else {
            mVV.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + fileRes));
            return true;
        }
    }

    private boolean playFileRes(String fileRes) {
        if (TextUtils.isEmpty(fileRes)) {
            stopPlaying();
            return false;
        } else {
//            mVV.setVideoURI(Uri.parse(fileRes));
            mVV.setVideoPath(getVideoCache(fileRes));
            return true;
        }
    }

    private String getVideoCache(String url) {
        HttpProxyCacheServer proxy = GlobalContext.getProxy();
        String proxyUrl = proxy.getProxyUrl(url);
        return proxyUrl;
    }

    public void stopPlaying() {
        mVV.stopPlayback();
        this.finish();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        finish();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        stopPlaying();
        return true;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.setLooping(true);
    }
}
